#include "control.h"
#include "ui_control.h"
#include <QString>
#include <QDebug>
#include <QMessageBox>
#include <QProcess>
#include <QRegularExpression>
control::control(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::control)
{
    ui->setupUi(this);
    timeTimer = new QTimer(this);
    connect(timeTimer, SIGNAL(timeout()), this, SLOT(showTimeMessage()));
    connect(ui->btn_scan, SIGNAL(clicked(bool)), this, SLOT(scanPort()));
    connect(ui->btn_open, SIGNAL(clicked(bool)), this, SLOT(openPort()));
    //connect(ui->btn_send, SIGNAL(clicked(bool)), this, SLOT(sendData()));
    timeTimer->start(1000);
    //设置默认值
    ui->cb_baud->setCurrentIndex(2);
    ui->cb_bit->setCurrentIndex(3);
    ui->pushButton->setEnabled(false); //发送按钮
      ui->pushButton_2->setEnabled(false); //发送按钮
      ui->pushButton_3->setEnabled(false); //发送按钮
      ui->pushButton_4->setEnabled(false); //发送按钮
    QString style = "QPushButton { color: blue; }";
    ui->pushButton->setStyleSheet(style);
     ui->pushButton_2->setStyleSheet(style);
    ui->pushButton_3->setStyleSheet(style);
   ui->pushButton_4->setStyleSheet(style);
   ui->UUIC->addItem("5");
       ui->UUIC->addItem("6");
       ui->UUIC->addItem("7");
       ui->UUIC->addItem("8");
       ui->UUIC->addItem("9");
       ui->UUIC->setCurrentIndex(0);

}

control::~control()
{
    delete ui;
}

// 显示时间
void control::showTimeMessage()
{
    QDateTime currentTime = QDateTime::currentDateTime();
    QString time = currentTime.toString("yyyy-MM-dd hh:mm:ss  ddd");
    ui->statusBar->showMessage(time);
}
//查找可用串口
void control::scanPort()
{
    ui->cb_port->clear();
    int isHavePort = 0;
    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        QSerialPort serial;
        serial.setPort(info);
        //判断端口能否打开
        if(serial.open(QIODevice::ReadWrite))
        {
            ui->cb_port->addItem(serial.portName());
            isHavePort++;
        }
        if(isHavePort == 0)
        {
            QMessageBox::information(NULL, "警告", "没有可用串口");
        }
    }
}

// 打开串口

void control::openPort()
{
    if(ui->btn_open->text() == tr("打开串口"))
    {
        serial = new QSerialPort;
        //设置串口名
        serial->setPortName(ui->cb_port->currentText());
        //打开串口
        bool isOpenSucc = serial->open(QIODevice::ReadWrite);
        if(isOpenSucc)
        {

            //设置波特率
            switch(ui->cb_baud->currentIndex())
            {
                case 0:
                    serial->setBaudRate(QSerialPort::Baud2400);
                    break;
                case 1:
                    serial->setBaudRate(QSerialPort::Baud4800);
                    break;
                case 2:
                    serial->setBaudRate(QSerialPort::Baud9600);
                    break;
                case 3:
                    serial->setBaudRate(QSerialPort::Baud19200);
                    break;
                case 4:
                    serial->setBaudRate(QSerialPort::Baud38400);
                    break;
                case 5:
                    serial->setBaudRate(QSerialPort::Baud57600);
                    break;
                case 6:
                    serial->setBaudRate(QSerialPort::Baud115200);
                    break;
                default:
                    break;
            }


            //设置数据位
            switch(ui->cb_bit->currentIndex())
            {
                case 0:
                    serial->setDataBits(QSerialPort::Data5);
                    break;
                case 1:
                    serial->setDataBits(QSerialPort::Data6);
                    break;
                case 2:
                    serial->setDataBits(QSerialPort::Data7);
                    break;
                case 3:
                    serial->setDataBits(QSerialPort::Data8);
                    break;
                default:
                    break;
            }
            //设置校验位
            switch(ui->cb_parity->currentIndex())
            {
                case 0:
                    serial->setParity(QSerialPort::NoParity);
                    break;
                case 1:
                    serial->setParity(QSerialPort::OddParity);
                    break;
                case 2:
                    serial->setParity(QSerialPort::EvenParity);
                default:
                    break;
            }
            //设置停止位
            switch(ui->cb_stop->currentIndex())
            {
                case 0:
                    serial->setStopBits(QSerialPort::OneStop);
                    break;
                case 1:
                    serial->setStopBits(QSerialPort::OneAndHalfStop);
                case 2:
                    break;
                    serial->setStopBits(QSerialPort::TwoStop);
                    break;
                default:
                    break;
            }
            //设置流控制
            serial->setFlowControl(QSerialPort::NoFlowControl);//设置为无流控制

            //关闭设置菜单使能
            ui->cb_port->setEnabled(false);
            ui->cb_baud->setEnabled(false);
            ui->cb_bit->setEnabled(false);
            ui->cb_parity->setEnabled(false);
            ui->cb_stop->setEnabled(false);
            ui->btn_open->setText(tr("关闭串口"));
            ui->pushButton->setEnabled(true);  //发送按钮
            ui->pushButton_2->setEnabled(true);
            ui->pushButton_3->setEnabled(true);
            ui->pushButton_4->setEnabled(true);
            connect(serial, SIGNAL(readyRead()), this, SLOT(readData()));
        }
        else
        {
            QMessageBox::information(NULL, "警告", "打开串口失败，串口可能被占用，请扫描可用串口。");
        }

    }
    else
    {
        //关闭串口
        serial->clear();
        serial->close();
        serial->deleteLater();
        //恢复设置菜单使能
        ui->cb_port->setEnabled(true);
        ui->cb_baud->setEnabled(true);
        ui->cb_bit->setEnabled(true);
        ui->cb_parity->setEditable(true);
        ui->cb_stop->setEnabled(true);
        ui->btn_open->setText(tr("打开串口"));
        ui->pushButton->setEnabled(false);  //发送按钮
        ui->pushButton_2->setEnabled(false);
        ui->pushButton_3->setEnabled(false);
        ui->pushButton_4->setEnabled(false);
    }
}

//读取接收到的信息
void control::readData()
{

    QByteArray buf =serial->readAll();//返回读取的字节
    if(!buf.isEmpty())
    {
        QString str = this->ui->te_recieve->toPlainText();

        ui->te_recieve->clear();
        ui->te_recieve->setText(str);
        QStringList parts = str.split(' ');

            QString tempStr, humiStr, lightStr;

            for (const QString &part : parts) {
                // 如果包含逗号，按逗号分割
                QStringList subparts = part.split(',');
                for (const QString &subpart : subparts) {
                    // 提取等号后面的数字部分
                    QString number = subpart.section('=', 1, 1);  // section('=', 1, 1) 表示提取等号后面的第1部分
                    if (!number.isEmpty()) {
                        if (subpart.startsWith("temp=")) {
                            tempStr = number;
                        } else if (subpart.startsWith("humi=")) {
                            humiStr = number;
                        } else if (subpart.startsWith("light=")) {
                            lightStr = number;
                        }
                    }
                }
            }

         ui->lineEdit_5->clear();
        ui->lineEdit_5->setText(humiStr);
        ui->lineEdit_9->clear();
       ui->lineEdit_9->setText(lightStr);
       ui->lineEdit_12->clear();
      ui->lineEdit_12->setText(tempStr);
        ui->te_recieve->moveCursor(QTextCursor::End);//移动光标
        //ui->te_recieve->insertPlainText(buf.toHex());
        ui->te_recieve->insertPlainText(buf);
        ui->te_recieve->moveCursor(QTextCursor::End);//移动光标
        ui->te_recieve->insertPlainText(" ");

    }
    buf.clear();
}

//将十进制int转换为十六进制字符串
QString control::decInt2HexStr(int dec)
{
    //保证数据在两帧范围内
    if(dec > 65535)
    {
        QMessageBox::information(NULL, "警告", "输入超出规定范围（input < 65535）");
        return "0";
    }
    QString hexStr;
    int temp = dec / 16;
    int left = dec % 16;
    if(temp > 0)
        hexStr += decInt2HexStr(temp);
    if(left < 10)
        hexStr += (left + '0');
    else
        hexStr += ('A' + left - 10);
    return hexStr;
}

//将输入格式化，补满四位：0XFFFF
QString control::formatInput(QString hexStr)
{
    int strlen = hexStr.length();
    switch(strlen)
    {
        case 0:
            hexStr = "0000";
            break;
        case 1:
            hexStr = "000" + hexStr;
            break;
        case 2:
            hexStr = "00" + hexStr;
            break;
        case 3:
            hexStr = "0" + hexStr;
            break;
        case 4:
            hexStr = hexStr;
            break;
        default:
            break;
    }
    return hexStr;
}

//字符串转Hex(QByteArray)类型
QByteArray control::QString2Hex(QString hexStr)
{
    QByteArray senddata;
    int hexdata, lowhexdata;
    int hexdatalen = 0;
    int len = hexStr.length();
    senddata.resize(len/2);
    char lstr, hstr;
    for(int i = 0; i < len; )
    {
        //将第一个不为' '的字符赋给hstr;
        hstr = hexStr[i].toLatin1();
        if(hstr == ' ')
        {
            i++;
            continue;
        }
        i++;
        //当i >= len时，跳出循环
        if(i >= len)
            break;
        //当i < len时，将下一个字符赋值给lstr;
        lstr = hexStr[i].toLatin1();
        //将hstr和lstr转换为0-15的对应数值
        hexdata = ConvertHexChar(hstr);
        lowhexdata = ConvertHexChar(lstr);
        //
        if((hexdata == 16) || (lowhexdata == 16))
            break;
        else
            hexdata = hexdata * 16 + lowhexdata;
        i++;
        senddata[hexdatalen] = (char)hexdata;
        hexdatalen++;
    }
    senddata.resize(hexdatalen);
    return senddata;
}

//将单个字符串转换为hex
//0-F -> 0-15
char control::ConvertHexChar(char c)
{
    if((c >= '0') && (c <= '9'))
        return c - 0x30;
    else if((c >= 'A') && (c <= 'F'))
        return c - 'A' + 10;//'A' = 65;
    else if((c >= 'a') && (c <= 'f'))
        return c - 'a' + 10;
    else
        return -1;
}
//发送数据  Add by zhaozy 2022-1-7
void control::on_pushButton_clicked()
{
    if(ui->lineEdit->text().isEmpty()){
        QMessageBox::information(this, tr("提示消息"), tr("没有需要发送的数据"), QMessageBox::Ok);
        return;
    }
    //发送数据
    serial->write(ui->lineEdit->text().toLatin1());
    ui->statusBar->showMessage(tr("发送数据成功"));
    ui->lineEdit->setFocus();
    ui->lineEdit->clear();
}

/*void control::on_pushButton_2_clicked()
{
    QString program=ui->lineEdit_4->text();
    QProcess *myProcess = new QProcess(this);
          myProcess->start(program);
}*/


void control::on_pushButton_2_clicked()
{
    if(ui->lineEdit_4->text().isEmpty()){
        QMessageBox::information(this, tr("提示消息"), tr("没有需要发送的数据"), QMessageBox::Ok);
        return;
    }
    //发送数据
    QByteArray data = "humidity threshold:";
    QByteArray byteArray = ui->lineEdit_4->text().toLatin1();
    data.append(byteArray);
    serial->write(data);
    //serial->write(ui->lineEdit_8->text().toLatin1());
    ui->statusBar->showMessage(tr("发送数据成功"));
    ui->lineEdit_4->setFocus();
    ui->lineEdit_4->clear();

}

void control::on_pushButton_3_clicked()
{
    if(ui->lineEdit_7->text().isEmpty()){
        QMessageBox::information(this, tr("提示消息"), tr("没有需要发送的数据"), QMessageBox::Ok);
        return;
    }
    //发送数据
    QByteArray data = "temperature threshold:";
    QByteArray byteArray = ui->lineEdit_7->text().toLatin1();
    data.append(byteArray);
    serial->write(data);
    //serial->write(ui->lineEdit_8->text().toLatin1());
    ui->statusBar->showMessage(tr("发送数据成功"));
    ui->lineEdit_7->setFocus();
    ui->lineEdit_7->clear();
}
void control::on_pushButton_4_clicked()
{
    if(ui->lineEdit_10->text().isEmpty()){
        QMessageBox::information(this, tr("提示消息"), tr("没有需要发送的数据"), QMessageBox::Ok);
        return;
    }
    //发送数据
    //QByteArray data = "light threshold:";
    QByteArray byteArray = ui->lineEdit_10->text().toLatin1();
    //qDebug() <<byteArray;//
    //data.append(byteArray);
    //serial->write(data);

    // binary1.append(binary2);

    //qDebug() << data;//
    //serial->write(ui->lineEdit_8->text().toLatin1());
    QList<QByteArray> parts =byteArray .split('-');

       if (parts.size() >= 2) {
           bool ok1, ok2;
           int num1 = parts[0].toInt(&ok1);  // 检查转换是否成功
           int num2 = parts[1].toInt(&ok2);
               QByteArray binary1 = QByteArray::number(num1, 2);
               QByteArray binary2 = QByteArray::number(num2, 2);

               // 补零至 8 位
               binary1 = QByteArray(8 - binary1.size(), '0') + binary1;
               binary2 = QByteArray(8 - binary2.size(), '0') + binary2;
               binary1.append(binary2);
               qDebug() <<binary1;
    ui->statusBar->showMessage(tr("发送数据成功"));
    ui->lineEdit_10->setFocus();
    ui->lineEdit_10->clear();

}

void control::on_cb_stop_2_activated(int index)
{

}
